import React, {Component} from 'react';

import {Platform, Button, View, Text, Image, FlatList, StyleSheet} from 'react-native';
import ExampleComponent from "../component/example-component";
import {extraUniqueKey} from "../utils/extraUniqueKey";
import {homeFetch} from "../provider/home.provider";

class LogoTitle extends Component {
    render() {
        return (
            <Text>Home</Text>
        );
    }
}

const headerButtonColor = Platform.select({
    ios: '#fff',
    android: 'blue'
});


export default class HomeScreen extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: [],
            count: 0,
            loaded: false,
        };
    }

    componentDidMount() {
        // 在ES6中，如果在自定义的函数里使用了this关键字，则需要对其进行“绑定”操作，否则this的指向会变为空
        // 像下面这行代码一样，在constructor中使用bind是其中一种做法（还有一些其他做法，如使用箭头函数等）
        return homeFetch().then((responseData) => {
            // 注意，这里使用了this关键字，为了保证this在调用时仍然指向当前组件，我们需要对其进行“绑定”操作
            let movies = [];
            for (let i = 0; i < 300; i++) {
                movies = movies.concat(responseData.movies)
            }
            this.setState({
                data: movies,
                loaded: true
            });
        },reason => {
            return null;
        }).catch((error) => {
            console.error(error);
        });
    }

    render() {
        let list = this.state.loaded?<FlatList
            keyExtractor={extraUniqueKey}
            data={this.state.data}
            renderItem={HomeScreen.renderMovie}
            style={styles.list}
        />:HomeScreen.renderLoadingView();
        return (
            <View style={{flex: 1, justifyContent: 'flex-start'}}>
                <Text>Home Screen</Text>
                <Text>count:{this.state.count}</Text>
                <Button
                    title="Go to Details"
                    onPress={() => {
                        /* 1. 跳到路由 Details 屏幕，传递了参数 */
                        this.props.navigation.navigate('Details', {
                            itemId: 86,
                            otherParam: 'anything you want here',
                        });
                    }}
                />
                <Button
                    title="事例"
                    onPress={() => {
                        /* 1. 跳到路由 Details 屏幕，传递了参数 */
                        this.props.navigation.navigate('Example');
                    }}
                />
                <ExampleComponent/>
                {list}
            </View>
        );
    }

    static navigationOptions = ({navigation}) => {
        const params = navigation.state.params || {};

        return {
            title: 'Home1',
            headerLeft: (
                <Button
                    onPress={() => navigation.navigate('MyModal')}
                    title="模态框"
                    color={headerButtonColor}
                />
            ),
            headerStyle: {
                backgroundColor: 'blue',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
                fontWeight: 'bold',
            },
            headerTitle: <LogoTitle/>,
            headerRight: (
                <View style={{flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
                    <Button
                        onPress={() => alert('标题内容', '正文内容',
                            [{text: "我知道了", onPress: this.confirm}]
                        )}
                        title="打印"
                        color={headerButtonColor}
                    />
                    <Button
                        onPress={params.increaseCount}
                        title="+1"
                        color={headerButtonColor}
                    />
                </View>

            )
        }
    };

    componentWillMount() {
        this.props.navigation.setParams({increaseCount: this._increaseCount});
    }

    _increaseCount = () => {
        this.setState({count: this.state.count + 1});
    };

    static renderLoadingView() {
        return (
            <View style={styles.container}>
                <Text>
                    Loading movies...
                </Text>
            </View>
        );
    }

    static renderMovie({item}) {
        return (
            <View style={styles.container}>
                <Image
                    source={{uri: item.posters.thumbnail}}
                    style={styles.thumbnail}
                />
                <View style={styles.rightContainer}>
                    <Text style={styles.title}>{item.title}</Text>
                    <Text style={styles.year}>{item.year}</Text>
                </View>
            </View>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    rightContainer: {
        flex: 1,
    },
    title: {
        fontSize: 20,
        marginBottom: 8,
        textAlign: 'center',
    },
    year: {
        textAlign: 'center',
    },
    thumbnail: {
        width: 53,
        height: 81,
    },
    list: {
        paddingTop: 20,
        backgroundColor: '#F5FCFF',
    },
});